package com.supostacks.infrastructure.context;

import java.lang.reflect.Field;


public class EntityUtil {

    public static void copyFields(Object source, Object target) throws IllegalAccessException {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        // Traverse the source class and its superclasses
        while (sourceClass != null) {
            Field[] fields = sourceClass.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Field targetField = getFieldByName(targetClass, field.getName());
                if (targetField != null) {
                    targetField.setAccessible(true);
                    targetField.set(target, field.get(source));
                }
            }
            sourceClass = sourceClass.getSuperclass();
        }
    }

    private static Field getFieldByName(Class<?> clazz, String fieldName) {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            // Field not found in this class, continue searching in superclass
            Class<?> superClass = clazz.getSuperclass();
            if (superClass != null) {
                return getFieldByName(superClass, fieldName);
            }
        }
        return null;
    }
}
